<template>
  <div>
    <el-select v-model="innerValue"
               :placeholder="$attrs.placeholder || '请选择字典值'"
               :clearable="$attrs.clearable != null ? $attrs.clearable : true"
               :multiple="multiple"
               @change="onchange"
               filterable
               reserve-keyword
               remote
               :remote-method="remoteMethod"
               :loading="loading">
      <el-option
        v-for="dict in innerOptions"
        :key="dict.value"
        :label="dict[labelKey]"
        :value="String(dict[valueKey])"
      />
    </el-select>
  </div>
</template>

<script>

export default {
  name: "RemoteSelect",
  props: {
    value: [Number, String, Array],
    multiple: {
      type: Boolean,
      default: false
    },
    valueKey: {
      default: 'id'
    },
    labelKey: {
      default: 'name'
    },
    remoteApi: {
      type: Function,
      required: true
    },
    //远端数据格式化
    dataFormatter: Function,
    initData: Array,
    searchKey: {
      type: String,
      required: true
    },
  },
  data() {
    return {
      loading: false,
      innerOptions: this.initData || [],
      innerValue: null
    }
  },
  methods: {
    initInnerValue() {
      let v = this.value
      if (v == null || v == 'undefined') {
        this.innerValue = null
        return;
      }
      if (!this.multiple) {
        this.innerValue = String(v)
        return;
      }
      const values = v.split(',')
      if (values.length > 0) this.innerValue = values
    },
    async onchange(value) {
      const v = await this.innerOptions.find(i => i[this.valueKey] == value)
      this.$emit("change", value, v)
    },
    async remoteMethod(value) {
      this.loading = true
      const data = {
        pageSize: 20,
        pageNum: 1,

      };
      data[this.searchKey] = value;
      const rsp = await this.remoteApi(data)
      this.innerOptions = this.dataFormatter ? this.dataFormatter(rsp) : (rsp.data.records ? rsp.data.records : rsp.data)
      console.log(this.innerOptions)
      this.loading = false
    }
  },
  watch: {
    innerValue(newData, oldData) {
      if (newData == oldData) return
      if (this.multiple) {
        newData = newData.length  ? newData.join(",") : null
      }
      this.$emit('input', newData);
    },
    value: {
      handler(newData) {
        this.initInnerValue();
      },
      immediate: true
    }
  },
};
</script>
<style scoped lang="scss">
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
